package com.example.concurrency.sync;

/**
 * synchronized是非公平锁，可重入锁
 */
public class SynchronizedDemo
{
    public synchronized void test1()
    {
        System.out.println("test1 start");
        try
        {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("test1 end");
    }

    public synchronized void test2()
    {
        System.out.println("test2 start");
        System.out.println("test2 end");
    }

    public static void main(String[] args)
    {
        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
        differenceMethodTest(synchronizedDemo);
    }

    /**
     * 不同线程调用同一个对象里面不同的synchronized方法，是会发生锁竞争的，
     * 因为synchronized修饰方法，锁是对象本身
     */
    private static void differenceMethodTest(SynchronizedDemo synchronizedDemo)
    {
        new Thread(synchronizedDemo::test1).start();
        new Thread(() ->
        {
            try
            {
                Thread.sleep(1 * 1000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            synchronizedDemo.test2();
        }).start();
    }
}
